<!-- 备件管理-备件基础数据页面-类型 -->
<template>
  <div>
    <px-form class="custom-form-ui equip-form" :model="queryParams" label-position="right" style="padding-top: 14px" label-width="120px">
      <px-row :gutter="16">
        <px-col :span="6">
          <px-form-item label="厂商型号">
            <px-input
              v-model="queryParams.supplyModel"
              placeholder="请输入厂商型号"
              maxlength="50"
              clearable
              @blur="queryParams.supplyModel = $event.target.value.trim()"
              @keyup.enter="queryTable"
            >
              <template #suffix>
                <px-icon style="cursor: pointer" @click="queryTable">
                  <search />
                </px-icon>
              </template>
            </px-input>
          </px-form-item>
        </px-col>
        <px-col :span="6">
          <px-form-item label="厂内型号">
            <px-input
              v-model="queryParams.model"
              placeholder="请输入厂内型号"
              maxlength="50"
              clearable
              @blur="queryParams.model = $event.target.value.trim()"
              @keyup.enter="queryTable"
            >
              <template #suffix>
                <px-icon style="cursor: pointer" @click="queryTable">
                  <search />
                </px-icon>
              </template>
            </px-input>
          </px-form-item> </px-col
        ><px-col :span="6">
          <px-form-item label="种类">
            <px-select v-model="queryParams.category" filterable clearable placeholder="请选择种类" @change="handleCategoryChange">
              <px-option v-for="item in categoryList" :key="item.value" :label="item.name" :value="item.value" />
            </px-select>
          </px-form-item> </px-col
        ><px-col :span="6">
          <px-form-item label="类型">
            <px-tree-select
              v-model="queryParams.typeCode"
              placeholder="请选择类型"
              filterable
              clearable
              :data="typeList"
              :render-after-expand="false"
              :props="defaultProps"
              @visible-change="initTypeList"
              @change="handleTypeChange"
            />
          </px-form-item>
        </px-col>
        <px-col :span="6">
          <px-form-item label="品牌">
            <px-select v-model="queryParams.brandCode" filterable clearable placeholder="请选择品牌" @focus="initBrandList">
              <px-option v-for="item in brandList" :key="item.code" :label="item.name" :value="item.code" />
            </px-select>
          </px-form-item>
        </px-col>
        <px-col :span="6">
          <px-button type="primary" @click="queryTable">查询</px-button>
          <px-button @click="resetTable">重置</px-button>
        </px-col>
      </px-row>
    </px-form>
    <div class="equip-table-btn">
      <px-button v-has="'ALL_EQUIP_SPAREPARTS_BASEDATA_ADD'" style="margin-right: 8px" type="primary" @click="addSpareParts">新增型号</px-button>
    </div>
    <px-table row-key="id" :data="tableData" class="equip-table" size="small" height="calc(100vh - 385px)" border>
      <px-table-column label="序号" width="80" align="center" fixed="left">
        <template #default="{ $index }">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
        </template>
      </px-table-column>
      <px-table-column
        v-for="(item, index) in tableColumns"
        :key="index"
        :label="item.label"
        :min-width="item.minWidth"
        :align="item.align"
        :show-overflow-tooltip="item.showOverflowTooltip"
        :fixed="item.fixed"
      >
        <template #default="scope">{{
          scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
        }}</template>
      </px-table-column>
      <px-table-column fixed="right" label="操作" width="100" align="center">
        <template #default="scope">
          <px-tooltip content="编辑" placement="top">
            <px-button v-has="'ALL_EQUIP_SPAREPARTS_BASEDATA_EDIT'" link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
          </px-tooltip>
          <px-tooltip content="删除" placement="top">
            <px-button v-has="'ALL_EQUIP_SPAREPARTS_BASEDATA_DELETE'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
          </px-tooltip>
        </template>
      </px-table-column>
    </px-table>
    <pagination
      v-show="total > 0"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      class="equip-table-pagination"
      :total="total"
      @pagination="queryTable"
    />
    <!-- 新增/修改抽屉 -->
    <AddModelDrawer
      :visible="sparePartsVisible"
      :drawerType="drawerType"
      :typeTitle="typeTitle"
      :sparePartsRow="sparePartsRow"
      @queryTable="queryTable"
      @closeDrawer="closeDrawer"
    />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ALL_EQUIP_SPAREPARTS_BASEDATA"
});
import { queryDictData } from "@/api/common";
import { delSparePartModel, queryListTree_1, queryBrandList, queryListPage_5 } from "@/api/equip/spareParts";
import { PxMessage, PxMessageBox } from "px-ui";
import { onMounted, reactive, toRefs } from "vue";
import AddModelDrawer from "./AddModelDrawer.vue";

// 树形选择图
const defaultProps = {
  children: "children",
  label: "name",
  value: "code"
};
// const { proxy }: any = getCurrentInstance();
const state = reactive<any>({
  queryParams: {
    typeOrCode: "",
    pageNum: 1,
    pageSize: 20
  },
  tableColumns: [
    { prop: "supplyModel", label: "厂商型号", minWidth: "120", showOverflowTooltip: true },
    { prop: "model", label: "厂内型号", minWidth: "120", showOverflowTooltip: true },
    { prop: "brandName", label: "品牌", minWidth: "120", showOverflowTooltip: true },
    { prop: "typeName", label: "类型", minWidth: "120", showOverflowTooltip: true },
    { prop: "categoryDesc", label: "种类", minWidth: "120", showOverflowTooltip: true },
    { prop: "createName", label: "创建人", minWidth: "120", showOverflowTooltip: true },
    { prop: "createTime", label: "创建时间", minWidth: "120", showOverflowTooltip: true }
  ],
  tableData: [],
  total: 0,
  categoryList: [],
  typeList: [],
  brandList: [],
  sparePartsVisible: false,
  drawerType: "add",
  typeTitle: "",
  sparePartsRow: {}
});
const { queryParams, tableColumns, tableData, total, categoryList, typeList, brandList, sparePartsVisible, drawerType, typeTitle, sparePartsRow } =
  toRefs(state);

// 进入页面时触发
onMounted(() => {
  queryTable();
  initCategory();
  initBrandList();
});

const props = defineProps(["activeName"]);
// 查询备件列表
const queryTable = async () => {
  const params = { ...queryParams.value, type: props.activeName };
  const data = await queryListPage_5(params);
  tableData.value = data?.data || [];
  total.value = data?.total;
};
// 种类改变，清空类型
const handleCategoryChange = () => {
  typeList.value = [];
  queryParams.value.typeCode = undefined;
};
// 种类下拉框
const initCategory = async () => {
  categoryList.value = [];
  const params = {
    typeCode: "typeCategory"
  };
  const data = await queryDictData(params);
  categoryList.value = data;
};
const setCategory = (list, params, val) => {
  list.forEach(item => {
    if (item.code === val) {
      params.value.category = item.category;
    } else if (item.children?.length) {
      setCategory(item.children, params, val);
    }
  });
};
// 类型改变，改变种类\品牌
const handleTypeChange = val => {
  if (!queryParams.value.category) {
    setCategory(typeList.value, queryParams, val);
  }
  queryParams.value.brandCode = undefined;
};
// 类型下拉框
const initTypeList = async flag => {
  if (flag) {
    const data = await queryListTree_1({ category: queryParams.value.category });
    typeList.value = data;
  } else {
    typeList.value = [];
  }
};
// 品牌下拉框
const initBrandList = async () => {
  const data: any = await queryBrandList({ pageSize: 9999 });
  brandList.value = data || [];
};
// 重置筛选条件和备件列表
const resetTable = async () => {
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  queryTable();
};
// 添加备件类型-显示抽屉
const addSpareParts = () => {
  drawerType.value = "add";
  typeTitle.value = "新增型号";
  const sort = tableData.value.length ? tableData.value.length : 0;
  sparePartsRow.value = { sort };
  sparePartsVisible.value = true;
};
// 编辑备件-显示抽屉
const handleEdit = (row: any) => {
  drawerType.value = "edit";
  typeTitle.value = "编辑型号";
  sparePartsRow.value = { ...row };
  sparePartsVisible.value = true;
};
// 添加/编辑备件-关闭抽屉
const closeDrawer = () => {
  sparePartsVisible.value = false;
};
// 删除备件
const handleDelete = async (row: any) => {
  // 1、不存在未解除的关联数据
  PxMessageBox.confirm(`是否删除该型号“${row.typeName}”`, "删除提示", {
    confirmButtonText: "确定删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await delSparePartModel(row.id);
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");
</style>
